<template>
  <div>
    <!-- 表格子组件 -->
    <!--   @selection-change="selectionChange"
    -->
    <slot name="top-actions"></slot>
    <el-table
      v-loading="loading"
      :height="tableHeight"
      style="width: 100%; border: 1px solid red"
      :data="tableData"
      @selection-change="handleSelectionChange"
      @sort-change="sortChange"
       :fit="autoFit"
      :header-cell-style="headerCellStyle"
    >
      <!-- 复选框列 -->
      <el-table-column
        type="selection"
        width="55"
        align="center"
        v-if="showSelection"
      ></el-table-column>
      <el-table-column
        v-for="(item, index) in tableHeaders"
        header-align="center"
        :label="item.title"
        :prop="item.prop"
        :align="item.align"
        :sortable="item.sortable"
        :key="index"
         :min-width="item.minWidth || 120"
      >
        <template slot-scope="scope">
          <!-- 其次是专门处理操作列 -->
          <div v-if="item.title == '操作'">
            <slot name="action"></slot>
          </div>
          <!-- 自定义渲染列 -->
          <div v-else-if="item.scopedSlots">
            <slot name="status" :row="scope.row" :column="scope.column"></slot>
          </div>
          <div v-else>
            <span> {{ scope.row[scope.column.property] }}</span>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <!-- <div class="pagination" style="margin-top: 15px; text-align: right">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
      >
      </el-pagination>
    </div> -->
  </div>
</template>

<script>
export default {
  props: {
    scope: Object,
    render: Function,
    tableHeaders: Array,
    tableData: Array,
    // 加载状态
    loading: {
      type: Boolean,
      default: false,
    },
    // 是否显示复选框列
    showSelection: {
      type: Boolean,
      default: false,
    },
    // 表头背景色
    headerBgColor: {
      type: String,
      default: "rgba(76, 110, 226, 0.08)",
    },
    // 表头文字颜色
    headerTextColor: {
      type: String,
      default: "#303133",
    },
    // 表头字体大小
    headerFontSize: {
      type: String,
      default: "14px",
    },
    // 单元格文字颜色
    cellTextColor: {
      type: String,
      default: "#606266",
    },
    // 单元格字体大小
    cellFontSize: {
      type: String,
      default: "14px",
    },
    // 是否显示斑马条纹
    stripe: {
      type: Boolean,
      default: false,
    },
    // 斑马条纹颜色
    stripeColor: {
      type: String,
      default: "#fafafa",
    },
    // 表格高度
    tableHeight: {
      type: String,
      default: "calc(100vh - 200px)",
    },
    // 添加自动适应容器宽度属性
    // 添加自动适应容器宽度属性
    autoFit: {
      type: Boolean,
      default: true,
    },
    // 分页配置
    pagination: {
      type: Object,
      required: true,
      default: () => ({
        total: 0,
        currentPage: 1,
        pageSize: 10,
      }),
    },
    // 是否显示分页组件
    showPagination: {
      type: Boolean,
      default: true,
    },
  },
  computed: {
    // 表头样式
    headerCellStyle() {
      return {
        "background-color": this.headerBgColor,
        color: this.headerTextColor,
        "font-size": this.headerFontSize,
        "font-weight": "500",
      };
    },
    // 单元格样式
    cellStyle() {
      return {
        color: this.cellTextColor,
        "font-size": this.cellFontSize,
      };
    },
  },
  watch: {
    // 监听pagination变化，确保页码在有效范围内
    pagination: {
      handler(newPagination) {
        // 确保总条数不为负数
        if (newPagination.total < 0) {
          console.warn("分页总条数不能为负数");
        }

        // 确保当前页码在有效范围内
        const totalPages =
          Math.ceil(newPagination.total / newPagination.pageSize) || 1;
        if (
          newPagination.currentPage < 1 ||
          newPagination.currentPage > totalPages
        ) {
          console.warn("页码超出有效范围");
        }
      },
      deep: true,
    },
  },
  methods: {
    // 处理每页显示条数变化
    handleSizeChange(pageSize) {
      // 当每页显示条数变化时，重置到第一页
      const newPagination = {
        ...this.pagination,
        pageSize: pageSize,
        currentPage: 1,
      };
      this.$emit("handleSizeChange", newPagination);
    },
    // 处理页码变化
    handleCurrentChange(currentPage) {
      const newPagination = {
        ...this.pagination,
        currentPage: currentPage,
      };
      this.$emit("handleCurrentChange", newPagination);
    },
    // 处理选择事件
    handleSelectionChange(selection) {
      console.log("子组件中选项变更了", selection);
      this.$emit("handleSelectionChange", selection);
    },
    // 排序事件
    sortChange({ column, prop, order }) {
      console.log("排序事件", column, prop, order);
      this.$emit("sortChange", { column, prop, order });
    },
    // 行样式
    rowClassName({ row, rowIndex }) {
      if (this.stripe && rowIndex % 2 === 1) {
        return "stripe-row";
      }
      return "";
    },
    // 渲染自定义内容
    renderContent(render, scope) {
      // 确保render是一个函数
      if (typeof render === "function") {
        // 创建渲染上下文
        const h = this.$createElement;
        // 调用render函数并获取结果
        const result = render(h, scope.row, scope.column, scope.$index);

        // 如果返回的是字符串，直接返回
        if (typeof result === "string") {
          return result;
        }

        // 如果返回的是VNode对象，我们需要转换为HTML字符串
        // 这里采用简化的处理方式
        if (result && result.tag) {
          // 创建一个临时容器
          const container = document.createElement("div");
          // 模拟渲染过程
          // 在实际生产环境中，可能需要更复杂的处理
          try {
            // 尝试将VNode对象转换为字符串表示
            if (result.tag === "el-button") {
              const props = result.data.attrs || {};
              const children = result.children || [];
              const text = children[0] || "";
              return `<el-button type="${props.type || "default"}" size="${
                props.size || "small"
              }">${text}</el-button>`;
            }
          } catch (e) {
            console.error("渲染自定义内容失败:", e);
          }
        }
      }
      // 如果无法渲染，返回空字符串
      return "";
    },
  },
  mounted() {
    // 如果启用斑马条纹，动态添加样式
    if (this.stripe) {
      const style = document.createElement("style");
      style.textContent = `.stripe-row { background-color: ${this.stripeColor} !important; }`;
      document.head.appendChild(style);
    }
  },
};
</script>

<style scoped>
::v-deep .el-table {
  transition: all 0.3s ease;
}

::v-deep .el-table th {
  transition: all 0.3s ease;
}

::v-deep .el-table td {
  transition: all 0.3s ease;
}

/* 隐藏滚动条 */
::v-deep .el-table__body-wrapper {
  overflow-x: auto;
  overflow-y: auto;
}

::v-deep .el-table__body-wrapper::-webkit-scrollbar {
  display: none;
}

::v-deep .el-table__body-wrapper {
  -ms-overflow-style: none;
  scrollbar-width: none;
}
/* 分页组件样式优化 */
.pagination {
  user-select: none;
}

/* 优化分页组件悬停效果 */
::v-deep .el-pagination button:hover {
  color: #409eff;
  border-color: #c6e2ff;
}

/* 当前页码高亮样式优化 */
::v-deep .el-pagination .el-pager li.active {
  color: #409eff;
}

/* 输入框聚焦样式 */
::v-deep .el-pagination .el-input__inner:focus {
  border-color: #409eff;
  outline: 0;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}
</style>
